!*******************************************************************************
!*** Subroutines to write XYZ format position file
!*******************************************************************************
subroutine writexyz
use prec
use cell
use iounits
use general
use wallinfo
use waterinfo
use H2MolInfo
implicit none
   !----------------------------------------------------------------------------
   integer :: i, j, idummy
   real(q) :: AxisTMP(3,3) = 0.D0
   !----------------------------------------------------------------------------
   forall (i=1:3) AxisTMP(i,i) = box(i)
   xyzfile = trim(outfile)//".xyz"
   open( ioout, file=xyzfile, status='unknown', action='write' )
   idummy = natom
   if ( LAddWalls ) idummy = idummy + sum(WallRemain)
   if ( lwater    ) idummy = idummy + nH2Oatom
   write( ioout, 100 ) idummy
   write( ioout, 200 ) trim(title)
   write( ioout, 300) EName( attyp(1) ), atpos(:, 1)
   write( ioout, 310)
   do i = 2, min(4,natom)
      write( ioout, 300) EName( attyp(i) ), atpos(:, i)
      write( ioout, 320) i-1, AxisTMP(:,i-1)
   enddo
   do i = 5, natom
      write( ioout, 350 ) EName( attyp(i) ), atpos(:, i)
   enddo
   do i = 1, nWallAtom
      if ( WallRemain(i).eq.1 ) write( ioout, 350 ) WallElement(WallIndex(WallTyp(i))), WallPos(:,i)
   enddo
   if (lwater) then
      do i = 1, nH2Oatom
         write(ioout, 350) H2OName(watertype(i)), waterpos(:,i)
      enddo
   endif
   if (LH2Mol) then
      do i = 1, nH2Atom
         write(ioout, 350) H2Name(H2MolType(i)), H2MolPos(:,i)
      enddo
   endif
   close( ioout )
   !
100 format( I8 )
200 format( A  )
300 format( A2, 3(1X, F16.10), $ )
310 format( " crystal_origin 0.0 0.0 0.0 crystal_images 1 1 1" )
320 format( " crystal_vector ", I2, 3(1x, F16.10) ) 
350 format( A2, 3(1X, F16.10)    )
999 format( 6x,"atposMol(:,", I2,") = (/ ", 2(F14.10,"D0,",1x), F14.10,"D0 /) !" ) 
   !
return
end subroutine
